package cn.springboot.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {
	
//	private static Logger log = LoggerFactory.getLogger(CookieUtil.class);
	/**
     * 设置cookie
     * @param name  cookie名字
     * @param value cookie值
     * @param maxAge cookie生命周期  以秒为单位
     */
    public static void addCookie(HttpServletResponse res,String name,String value,int maxAge,String domain){
        try {
            value = URLEncoder.encode(""+value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        
        Cookie cookie = new Cookie(name, value + "" );
        cookie.setPath("/");
        /**
         *  tomcat8.5
         *  domain规则如下 
			1、必须是1-9、a-z、A-Z、. 、- （注意是-不是_）这几个字符组成 
			2、必须是数字或字母开头
			使用.test.com报错就是因为使用”.”开头
			3、必须是数字或字母结尾
         */
        cookie.setDomain(domain);
        if(maxAge>0)  cookie.setMaxAge(maxAge);
        res.addCookie(cookie);
    }
    
    /**
     * 根据名字获取cookie
     * @param name cookie名字
     * @return
     */
    public static Cookie getByName(HttpServletRequest req,String name){
        Map<String,Cookie> cookieMap = getCookieMap(req);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }   
    }
    
    /**
     * 将cookie封装到Map里面
     * @return
     */
    private static Map<String,Cookie> getCookieMap(HttpServletRequest req){  
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = req.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

    
    public static boolean delCookie(HttpServletRequest req,HttpServletResponse res,String cookieName) {   
        if (cookieName != null) {
            Cookie cookie = getCookie(req,cookieName);   
            if(cookie!=null){
                cookie.setMaxAge(0);//0，就立即删除   
                cookie.setPath("/");//不要漏掉   
                cookie.setDomain(req.getServerName());
                res.addCookie(cookie);   
                return true;   
            }
        }   
        return false;   
    }

    public static String getValueByName(HttpServletRequest req,String cookieName){
        Cookie cookie = getCookie(req,cookieName);
        return getValueByCookie(cookie);
    }
    
    public static String getValueByCookie(Cookie cookie){
        if(null == cookie) return null;
        try {
            return URLDecoder.decode(cookie.getValue(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    
    public static Cookie getCookie(HttpServletRequest req,String cookieName){   
        Cookie[] cookies = req.getCookies();   
        Cookie cookie = null;   
        try {
            if (cookies != null && cookies.length > 0) {   
                for (int i = 0; i < cookies.length; i++) {
                    cookie = cookies[i];   
                    if (cookie.getName().equals(cookieName)) {   
                        return cookie;   
                    }   
                }   
            }   
        } catch (Exception e) {  
            e.printStackTrace();   
        }
        return null;   
    }   
	
	/**
     * 判断元素是否为空
     * <p>
     * 目前可以判断一下元素
     * <ul>
     * <li>Collection,使用其isEmpty()</li>
     * <li>Map,使用其isEmpty()</li>
     * <li>Object[],判断length==0</li>
     * <li>String,使用.trim().length()效率高</li>
     * <li>Enumeration,使用hasMoreElements()</li>
     * <li>Iterator,使用hasNext()</li>
     * </ul>
     * 
     * @param value
     *            可以是Collection,Map,Object[],String,Enumeration,Iterator类型
     * @return 空返回true
     * @since 1.0
     */
    @SuppressWarnings("rawtypes")
	public final static boolean isNullOrEmpty(Object value){
        if (null == value){
            return true;
        }
        /*****************************************************************************/
        boolean flag = false;
        // 集合
        if (value instanceof Collection){
            flag = ((Collection) value).isEmpty();
        }
        // map
        else if (value instanceof Map){
            flag = ((Map) value).isEmpty();
        }
        // Object[]object数组
        else if (value instanceof Object[]){
            flag = ((Object[]) value).length == 0;
        }
        // 字符串
        else if (value instanceof String){
            // 比较字符串长度, 效率高
            flag = value.toString().trim().length() <= 0;
        }
        // 枚举
        else if (value instanceof Enumeration){
            flag = !((Enumeration) value).hasMoreElements();
        }
        // Iterator迭代器
        else if (value instanceof Iterator){
            flag = !((Iterator) value).hasNext();
        }
        return flag;
    }
}
